package com.carb.controller.admin;

import com.carb.constant.MessageConstant;
import com.carb.context.UserContext;
import com.carb.dto.UserLoginDTO;
import com.carb.dto.UserUpdateDTO;
import com.carb.entity.User;
import com.carb.exception.FileUploadFailedException;
import com.carb.result.Result;
import com.carb.service.IUserService;
import com.carb.utils.AliOssUtils;
import com.carb.vo.UserLoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController("adminCommonController")
@RequestMapping("/admin/common")
@Tag(name = "通用接口")
@Slf4j
public class CommonController {

    @Resource
    private AliOssUtils aliOssUtils;

    @Resource
    private IUserService userService;

    /**
     * 用户登录
     * @param userLoginDTO 用户登录时传递的数据模型
     * @return Result-UserLoginVO
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录信息：{}", userLoginDTO);
        UserLoginVO userLoginVO = userService.login(userLoginDTO);
        log.info("用户登录成功：{}", userLoginVO);
        return Result.success(userLoginVO);
    }

    /**
     * 文件上传
     * @param file 文件
     * @return 文件访问路径
     */
    @PostMapping("/upload")
    @Operation(summary = "文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传：{}", file);
        if (file == null) {
            throw new FileUploadFailedException(MessageConstant.FILE_NOT_FOUND);
        }

        // 1、原始文件名
        String originalFilename = file.getOriginalFilename();

        // 2、截取原始文件名后缀
        String extension = null;
        if (originalFilename != null) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        // 3、构造新文件名
        String newFileName = UUID.randomUUID() + extension;

        // 4、文件请求路径
        try {
            String filePath = aliOssUtils.upload(file.getBytes(), newFileName);
            return Result.success(filePath);
        } catch (IOException ex) {
            throw new FileUploadFailedException(MessageConstant.FILE_UPLOAD_FAILED);
        }
    }


    /**
     * 获取当前登录用户信息
     * @return 用户信息
     */
    @GetMapping("/me/profile")
    @Operation(summary = "获取当前登录用户信息")
    public Result<User> getCurrentUser() {
        Long userId = UserContext.getUserId();
        log.info("获取当前登录用户信息：{}", userId);
        User user = userService.getUserById(userId);
        log.info("获取当前登录用户信息成功：{}", user);
        return Result.success(user);
    }

    /**
     * 修改当前登录用户信息
     * @param userUpdateDTO 修改的当前登录用户信息
     */
    @PutMapping("/me/profile")
    @Operation(summary = "修改当前登录用户信息")
    public Result<String> updateCurrentUser(@RequestBody UserUpdateDTO userUpdateDTO) {
        userUpdateDTO.setId(UserContext.getUserId());
        log.info("修改当前登录用户信息：{}", userUpdateDTO);
        userService.updateUser(userUpdateDTO);
        log.info("修改当前登录用户信息成功！");
        return Result.success();
    }

    /**
     * 修改当前登录用户密码
     * @param password 新密码
     */
    @PostMapping("/me/password/{password}")
    @Operation(summary = "修改当前登录用户密码")
    public Result<String> updateCurrentUserPassword(@PathVariable @Parameter(description = "新密码") String password) {
        Long userId = UserContext.getUserId();
        log.info("修改当前登录用户密码，用户id：{}，新密码：{}", userId, password);
        userService.updatePassword(userId, password);
        log.info("修改当前登录用户密码成功！");
        return Result.success();
    }

}
